package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.mysql.jdbc.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        // 获取四种类型的sql操作标签：crud
        List<Element> list = new ArrayList<>();
        String[] sqlNodeArray = {"select", "update", "delete", "insert"};
        for (String node : sqlNodeArray) {
            String exp = "//" + node;
            list.addAll(rootElement.selectNodes(exp));
        }

        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            // 解析sql语句类型，并存储到mappedStatement中
            mappedStatement.setSqlType(getSqlType(sqlText));
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);

        }

    }

    /**
     * 解析sql语句类型：insert、update、delete、select、
     * @param sqlText
     * @return
     */
    private String getSqlType(String sqlText) {
        String type = null;

        if (sqlText.toLowerCase().startsWith("insert")) {
            type = "insert";
        } else if (sqlText.toLowerCase().startsWith("update")) {
            type = "update";
        } else if (sqlText.toLowerCase().startsWith("delete")) {
            type = "delete";
        } else if (sqlText.toLowerCase().startsWith("select")) {
            type = "select";
        } else {
            throw new RuntimeException("无法识别的sql语句类型");
        }

        return type;
    }


}
